package com.trainingcloud.action.document;

import com.trainingcloud.action.BaseSessionAction;
import com.trainingcloud.dao.DocumentDAO;
import com.trainingcloud.dao.FavoriteDAO;
import com.trainingcloud.entity.Document;
import com.trainingcloud.exception.DAOException;
import com.trainingcloud.exception.SystemException;

public class FavoriteAction extends BaseSessionAction 
{
	private String documentIds;
	private String action;
	
	public FavoriteAction() throws SystemException 
	{
		super();
	}

	@Override
	public String callWithSession() throws DAOException, SystemException 
	{
		if(documentIds.isEmpty())
		{
			return "Empty document id list.";
		}
		
		String[] documentIdList = documentIds.split(",");
		
		DocumentDAO documentDAO = new DocumentDAO();
		FavoriteDAO favoriteDAO = new FavoriteDAO();
		for(int i=1; i<=documentIdList.length; i++)
		{
			int documentId = Integer.parseInt(documentIdList[i-1]);
			
			Document document = documentDAO.getDocumentById(documentId);
			if(document==null)
			{
				return "Invalid document id.";
			}
			if(action.compareTo("insert")==0)
			{
				favoriteDAO.insertFavorite(currentUser.getId(), documentId);
			}
			else if(action.compareTo("remove")==0)
			{
				favoriteDAO.deleteFavorite(currentUser.getId(), documentId);
			}
			else
			{
				return "Invalid action.";
			}
		}
		return null;
	}

	public String getDocumentIds() {
		return documentIds;
	}

	public void setDocumentIds(String documentIds) {
		this.documentIds = documentIds;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

}
